import { _decorator, Component, ERaycast2DType, EventTouch, Graphics, instantiate, Intersection2D, Node, PhysicsSystem2D, PolygonCollider2D, UITransform, v2, v3, Vec2, Vec3 } from 'cc';
import { cutObj } from './cutObj';
const { ccclass, property } = _decorator;


// export enum EColor {
//     RED = "#FF0000",
//     GREEN = "#00FF00",
// }

@ccclass('cutHandler')
export class cutHandler extends Component {
    @property(Node) touchRoot: Node = null

    _graphic: Graphics = null
    start() {
        this._graphic = this.node.getComponent(Graphics)
        if (!this._graphic) {
            console.error("without graphic...", this.node, this.getComponent(Graphics))
            return
        }

        // let tColor = new Color()
        // tColor.fromHEX(EColor.RED)

        //添加点击拖动事件
        this.touchRoot.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
        this.touchRoot.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.touchRoot.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
    }

    _startPos: Vec2 = v2()
    _touchPos: Vec3 = v3()
    onTouchStart(e: EventTouch) {
        this._graphic.clear();
        const startPoint = this._startPos = e.getUILocation();
        this._touchPos.set(startPoint.x, startPoint.y, 0);
        this._touchPos = this.touchRoot.getComponent(UITransform).convertToNodeSpaceAR(this._touchPos)
        this._graphic.moveTo(this._touchPos.x, this._touchPos.y);
    }

    _movePos: Vec3 = v3()
    onTouchMove(e: EventTouch) {
        let uiPos = e.getUILocation()
        this._movePos.set(uiPos.x, uiPos.y, 0)
        this._movePos = this.touchRoot.getComponent(UITransform).convertToNodeSpaceAR(this._movePos)
        this._graphic.lineTo(this._movePos.x, this._movePos.y);
        // console.log("lineto ::", e.getUILocation(), e.getLocationX(), e.getLocationY())

        this._graphic.stroke();
    }

    onTouchEnd(e: EventTouch) {
        this._graphic.clear();
        this.tryCutObj(this._startPos, e.getUILocation());
    }

    /**尝试切割 (纯色物件) */
    tryCutObj(p1: Vec2, p2: Vec2) {

        // this._rayA.d = v3(p2.x - p1.x, p2.y - p1.y, 0).normalize()
        let resultA = PhysicsSystem2D.instance.raycast(p1, p2, ERaycast2DType.Closest)
        let resultB = PhysicsSystem2D.instance.raycast(p2, p1, ERaycast2DType.Closest)

        if (resultA.length == 0 || resultB.length == 0) {
            console.warn("catch nothing ...")
            return
        }

        if (resultA[0].collider != resultB[0].collider) {
            console.warn("catch error ...")
            return
        }

        console.log("被切割的物体::", resultA, resultA[0].collider.node.name)
        //转换成被切割物体内部点
        let collider = resultA[0].collider.node.getComponent(PolygonCollider2D)
        if (!collider) {
            console.warn("catch error has no PolygonCollider2D ...")
            return
        }

        // let tColor = new Color()
        // tColor.fromHEX("#00ff00")

        // if(collider.node.getComponent(PhysicsPolygonCollider2D))
        let localPointA = v2()
        let localPointB = v2()
        collider.body.getLocalPoint(resultA[0].point, localPointA);
        collider.body.getLocalPoint(resultB[0].point, localPointB);
        console.log("resulut ::", localPointA, localPointB)

        //寻找相交的边的索引
        let checkAllPoints = collider.points
        let edgeIdxA = null
        let edgeIdxB = null
        for (let i = 0; i < checkAllPoints.length; i++) {
            let p1 = checkAllPoints[i]
            let p2 = (i === checkAllPoints.length - 1) ? checkAllPoints[0] : checkAllPoints[i + 1]
            if (this.checkPointOnLine(localPointA, p1, p2)) {
                edgeIdxA = i
            }
            if (this.checkPointOnLine(localPointB, p1, p2)) {
                edgeIdxB = i
            }
        }
        console.log("cur idx ::", edgeIdxA, edgeIdxB, checkAllPoints.length)

        //分离形状的顶点
        const shapeA: Array<Vec2> = []
        const shapeB: Array<Vec2> = []
        let time = 0 //第几次遇到交接点
        for (let i = 0; i < checkAllPoints.length; i++) {
            let tPos = checkAllPoints[i].clone()
            if (time == 0) {
                shapeA.push(tPos)
            } else {
                shapeB.push(tPos)
            }

            if (i == edgeIdxA || i == edgeIdxB) {
                let curPoint = i === edgeIdxA ? localPointA.clone() : localPointB.clone()
                shapeA.push(curPoint)
                shapeB.push(curPoint)
                if (time == 0) {
                    time = 1
                } else {
                    time = 0
                }
            }
        }

        console.log("shapeA ::", collider.points, shapeA)
        //A
        collider.points = shapeA
        collider.apply()
        collider.node.getComponent(cutObj).refresh()
        //B
        let newObj = instantiate(collider.node)
        collider.node.parent.addChild(newObj)
        let newBCollider = newObj.getComponent(PolygonCollider2D)
        newBCollider.points = shapeB
        newBCollider.apply()
        newObj.getComponent(cutObj).refresh()


        // const points = collider.points

    }

    /**支持多个物体 */
    tryCutMulObj(p1: Vec2, p2: Vec2) {

    }

    checkPointOnLine(point, lineA, lineB) {
        const checkDis = 1;
        return Intersection2D.pointLineDistance(point, lineA, lineB, true) < checkDis
    }


}


